﻿using System.Web.Http;
using BotDetector.Core.Search;
using BotDetector.Core.Model;
using BotDetector.WebApplication.Models;
using System.Web;

namespace BotDetector.WebApplication.Controllers
{
    [RoutePrefix("api/request")]
    public class RequestController : ApiController
    {
        private const string BingSearchEngine = "Bing";
        private const string GoogleSearchEngine = "Google";
        private const string BothSearchEngines = "Both";

        private BingSearch BingSearch = new BingSearch();
        private GoogleSearch GoogleSearch = new GoogleSearch();
        private BotDetector.Core.Detector.BotDetector BotDetector = new BotDetector.Core.Detector.BotDetector();


        //Request format should be: http://localhost:29131/api/request/q=cel%20mai%20tare%20site%20de%20amuzament/searchEngine=Google
        [Route("{q}/{searchEngine}")]
        public Request Get(string q, string searchEngine)
        {
            ResultItemList resultItemList = new ResultItemList();
            resultItemList = Search(q, searchEngine);
            resultItemList.Phrase = q;
            bool isBot=BotDetector.IsBot(resultItemList);
            return new Request(){IsBot  = isBot.ToString()};
        }

        private ResultItemList Search(string q, string searchEngine)
        {
            ResultItemList resultItemList = new ResultItemList();

            switch (searchEngine)
            {
                case BingSearchEngine:
                    resultItemList = BingSearch.Search(q);
                    break;
                case GoogleSearchEngine:
                    resultItemList = GoogleSearch.Search(q);
                    break;
                case BothSearchEngines:
                    resultItemList = SearchAndAggregateGoogleAndBingResults(q);
                    break;
                default:
                    resultItemList = BingSearch.Search(q);
                    break;
            }
            return resultItemList;
        }

        private ResultItemList SearchAndAggregateGoogleAndBingResults(string q)
        {
            ResultItemList bingResultItemList = BingSearch.Search(q);
            ResultItemList googleResultItemList = GoogleSearch.Search(q);
            GoogleBingAggregator aggregator = new GoogleBingAggregator();
            return aggregator.AggregateGoogleAndBingResultsItemLists(googleResultItemList, bingResultItemList);
            
        }
    }
}
